package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    /**
     * 1.创建一个线程池对象  -- 它要处理我们自定义事件
     */
    private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 存储host和client的关联
     */
    private static final Map<String, RpcClient> HOST_AND_CLIENT_MAP = new HashMap<>(6);

    public static void clientBuild(List<String> childrenHost) {
        if (childrenHost.size() > 0) {
            childrenHost.forEach(childHost -> {
                String[] arr = childHost.split("#");
                //ip#port#time
                String ip = arr[0];
                String port = arr[1];
                System.out.println("开始建立连接 ip:" + ip + " port:" + port);
                RpcClient client = new RpcClient(ip, Integer.parseInt(port));
                HOST_AND_CLIENT_MAP.put(childHost, client);
            });
        }
    }


    public static Object createProxy(Class serviceClass, String childHost) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1)初始化客户端client
//                        RpcClient client = HOST_AND_CLIENT_MAP.get(childHost);
//                        System.out.println("HOST:"+childHost + " " + client.getInfo());
//                        UserClientHandler userClientHandler = client.getUserClientHandler();
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
//                        RpcClient rpcClient = new RpcClient("127.0.0.1", 8899);
                        RpcClient rpcClient = HOST_AND_CLIENT_MAP.get(childHost);
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
//                            rpcClient.close();
                        }

                    }
                });
    }
}
